# -*- coding: utf-8 -*-
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest
import os

class Untitled(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.base_url = "http://localhost/php4dvd/"
        self.verificationErrors = []
        self.accept_next_alert = True
    
    def test_untitled(self):
        driver = self.driver
        driver.get(self.base_url)
        driver.implicitly_wait(20)

        #Вход в систему
        user = driver.find_element_by_id("username")
        user.clear()
        user.send_keys("admin")
        pas = driver.find_element_by_name("password")
        pas.clear()
        pas.send_keys("admin")
        driver.find_element_by_name("submit").click()

        #Получение количества уже добавленных фильмов
        search = driver.find_element_by_id("q")
        search.clear()
        search.send_keys(Keys.RETURN)
        count = len(driver.find_elements_by_xpath("//div[starts-with(@id, 'movie_')]"))

        #Добавление нового фильма
        driver.find_element_by_css_selector("img[alt=\"Add movie\"]").click()
        form = driver.find_element_by_id("updateform")

        #Проверка поля IMDb number
        imdbid = form.find_element_by_name("imdbid")
        imdbid.clear()
        imdbid.send_keys("invalid")
        imdbid.send_keys(Keys.RETURN)
        assert driver.find_element_by_xpath("//label[@for='imdbid' and text()='Please enter a valid number']").is_displayed(), \
        "There is no warning message for field 'IMDb number'"

        #Проверка поля Title
        title = form.find_element_by_name("name")
        title.clear()
        assert driver.find_element_by_xpath("//label[@for='name' and text()='This field is required']").is_displayed(), \
        "There is no warning message for field 'Title'"

        #Проверка поля Year
        year = form.find_element_by_name("year")
        year.clear()
        assert driver.find_element_by_xpath("//label[@for='year' and text()='This field is required']").is_displayed(), \
        "There is no warning message for field 'Year'"
        year.send_keys("invalid")
        year.send_keys(Keys.RETURN)
        assert driver.find_element_by_xpath("//label[@for='year' and text()='Please enter a valid number']").is_displayed(), \
        "There is no warning input format message for field 'Year'"

        #Проверка поля Duration (minutes)
        dur = form.find_element_by_name("duration")
        dur.clear()
        dur.send_keys("invalid")
        dur.send_keys(Keys.RETURN)
        assert driver.find_element_by_xpath("//label[@for='duration' and text()='Please enter a valid number']").is_displayed(), \
        "There is no warning message for field 'Duration (minutes)'"

        #Проверка поля Rating
        rat = form.find_element_by_name("rating")
        rat.clear()
        rat.send_keys("invalid")
        rat.send_keys(Keys.RETURN)
        assert driver.find_element_by_xpath("//label[@for='rating' and text()='Please enter a valid number']").is_displayed(), \
        "There is no warning message for field 'Duration (minutes)'"

        #Проверка поля Trailer URL
        trail = form.find_element_by_name("trailer")
        trail.clear()
        trail.send_keys("invalid")
        trail.send_keys(Keys.RETURN)
        assert driver.find_element_by_xpath("//label[@for='trailer' and text()='Please enter a valid url (http://...)']").is_displayed(), \
        "There is no warning message for field 'Trailer URL'"

        #Заполнение корректными данными и сохранение
        imdbid.clear()
        imdbid.send_keys("12345")
        imdbid.send_keys(Keys.RETURN)
        assert not driver.find_element_by_xpath("//label[@for='imdbid' and text()='Please enter a valid number']").is_displayed(), \
        "There is warning message for positive data. Field 'IMDb number'"

        title.clear()
        title.send_keys("12345")
        title.send_keys(Keys.RETURN)
        assert not driver.find_element_by_xpath("//label[@for='name' and text()='This field is required']").is_displayed(), \
        "There is warning message for positive data. Field 'Title'"

        year.clear()
        year.send_keys("12345")
        year.send_keys(Keys.RETURN)
        assert not driver.find_element_by_xpath("//label[@for='year']").is_displayed(), \
        "There is warning message for positive data. Field 'Year'"
        #assert not driver.find_element_by_xpath("//label[@for='year' and text()='Please enter a valid number']").is_displayed(), \
        #"There is warning message for positive data. Field 'Year'"

        dur.clear()
        dur.send_keys("12345")
        dur.send_keys(Keys.RETURN)
        assert not driver.find_element_by_xpath("//label[@for='duration' and text()='Please enter a valid number']").is_displayed(), \
        "There is warning message for positive data. Field 'Duration'"

        rat.clear()
        rat.send_keys("12345")
        rat.send_keys(Keys.RETURN)
        assert not driver.find_element_by_xpath("//label[@for='rating' and text()='Please enter a valid number']").is_displayed(), \
        "There is warning message for positive data. Field 'Rating'"

        trail.clear()
        trail.send_keys("http://www.google.com")
        trail.send_keys(Keys.RETURN)
        #assert not driver.find_element_by_xpath("//label[@for='trailer']").is_displayed(), \
        #"There is warning message for positive data. Field 'Trailer URL'"

      #  driver.find_element_by_css_selector("img[alt=\"Save\"]").click()
       # driver.find_element_by_link_text("Home").click()
        for i in range(2):
            try:
                driver.find_element_by_css_selector("img[alt=\"Save\"]").click()
                break
            except:
                time.sleep(1)
                pass

        for i in range(2):
            try:
                driver.find_element_by_link_text("Home").click()
                break
            except:
                time.sleep(1)
                pass


        #Очистка результатов предыдущего поиска
        search = driver.find_element_by_id("q")
        search.clear()
        search.send_keys(Keys.RETURN)

        #Проверка добавления нового фильма
        assert len(driver.find_elements_by_xpath("//div[starts-with(@id, 'movie_')]")) == count + 1, "The movie was not added!"

        #Завершение теста
        driver.quit()

    
    def is_element_present(self, how, what):
        try: self.driver.find_element(by=how, value=what)
        except NoSuchElementException, e: return False
        return True
    
    def is_alert_present(self):
        try: self.driver.switch_to_alert()
        except NoAlertPresentException, e: return False
        return True
    
    def close_alert_and_get_its_text(self):
        try:
            alert = self.driver.switch_to_alert()
            alert_text = alert.text
            if self.accept_next_alert:
                alert.accept()
            else:
                alert.dismiss()
            return alert_text
        finally: self.accept_next_alert = True
    
    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()
